package com.nantai.jiafang.nantaijiafang.zhijian.fragment;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.blankj.utilcode.util.StringUtils;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.ViewModel.Zhijian_Net;
import com.nantai.jiafang.nantaijiafang.base.BaseFragment;
import com.nantai.jiafang.nantaijiafang.bean.ZhiJjian.AllDefects;
import com.nantai.jiafang.nantaijiafang.databinding.FragmentZhijianAlldefectsItemBinding;
import com.nantai.jiafang.nantaijiafang.databinding.FragmentZhijianDefectsBinding;
import com.nantai.jiafang.nantaijiafang.view.AddAndSubView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.util.LogUtil;

import java.util.List;

/**
 * 提取疵点描述界面
 */
public class ZhijianFragment_Defects extends BaseFragment<FragmentZhijianDefectsBinding> {
    private FragmentZhijianDefectsBinding mbinding;
    private GridViewAdapter gridViewAdapter;
    private int sum;
    private String initstr;

    @Override
    public int setlayoutid() {
        return R.layout.fragment_zhijian_defects;
    }

    @Override
    public void initUI(FragmentZhijianDefectsBinding binding) {
        EventBus.getDefault().register(this);
        mbinding = binding;
        Zhijian_Net.getAllDefects(this.getContext().getApplicationContext(), new Zhijian_Net.GetSingData<List<AllDefects>>() {
            @Override
            public void success(List<AllDefects> s) {
                gridViewAdapter = new GridViewAdapter(getContext(), s);
                 gridViewAdapter.setDefects(initstr);
                binding.gridViewDefects.setAdapter(gridViewAdapter);
            }
        });

        mbinding.btnDefectsBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
            }
        });
        mbinding.btnDefectsEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (gridViewAdapter != null) {
//                   if (gridViewAdapter.getsum()==sum && gridViewAdapter.getresult().length()>0){
//                       ZhijianFragment_detail_add fragment=(ZhijianFragment_detail_add)getActivity().getSupportFragmentManager().findFragmentByTag("ZhijianFragment_detail_add");
//                       fragment.setdefectDes(gridViewAdapter.getresult());
//                       fragment.setADefectNo(gridViewAdapter.getsum()+"");
//                       getFragmentManager().popBackStack();
//                   }else{
//                       Toast.makeText(getContext(), "实疵点数与选择的点数不匹配！", Toast.LENGTH_SHORT).show();
//                   }
                    ZhijianFragment_detail_add fragment = (ZhijianFragment_detail_add) getActivity().getSupportFragmentManager().findFragmentByTag("ZhijianFragment_detail_add");
                   String result = gridViewAdapter.getresult();
                    int sum = gridViewAdapter.getsum();
                    LogUtil.e("result = "+result);
                    LogUtil.e("sum = "+sum);
                    fragment.setdefectDes(result);
                    fragment.setADefectNo(sum+"");
                    /*fragment.setdefectDes(gridViewAdapter.getresult());
                    fragment.setADefectNo(gridViewAdapter.getsum()+"");*/
                    getFragmentManager().popBackStack();
                }
            }
        });
    }


    public class GridViewAdapter extends BaseAdapter {
        public LayoutInflater inflater;
        public List<AllDefects> defects;

        //public List<Integer> results=new ArrayList<>();
        public GridViewAdapter(Context context, List<AllDefects> defects) {
            inflater = LayoutInflater.from(context);
            this.defects = defects;
           /* for (int i = 0; i < defects.size(); i++) {
                results.add(0);
            }*/
        }

        @Override
        public int getCount() {
            return defects.size();
        }

        @Override
        public AllDefects getItem(int position) {
            return defects.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            AllDefects currStr = getItem(position);

            FragmentZhijianAlldefectsItemBinding fragmentZhijianAlldefectsItemBinding;
//            if(convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            fragmentZhijianAlldefectsItemBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_zhijian_alldefects_item, null, false);
            convertView = fragmentZhijianAlldefectsItemBinding.getRoot();
            fragmentZhijianAlldefectsItemBinding.setAllDefects(currStr);
            convertView.setTag(fragmentZhijianAlldefectsItemBinding);
            if (defects.get(position).getNum() != 0) {
                fragmentZhijianAlldefectsItemBinding.Defectsnumber.setNum(defects.get(position).getNum());
                // results.set(position,defects.get(position).getNum());
            } else {
                //results.set(position,0);
            }

            fragmentZhijianAlldefectsItemBinding.Defectsnumber.setOnNumChangeListener(new AddAndSubView.OnNumChangeListener() {
                @Override
                public void onNumChange(View view, int num) {
                    defects.get(position).setNum(fragmentZhijianAlldefectsItemBinding.Defectsnumber.getNum());
                    //results.set(position,fragmentZhijianAlldefectsItemBinding.Defectsnumber.getNum());
                }
            });
            convertView.setTag(fragmentZhijianAlldefectsItemBinding);
//            }else {

//                fragmentZhijianAlldefectsItemBinding = (FragmentZhijianAlldefectsItemBinding) convertView.getTag();
//            }

            return convertView;
        }

        public String getresult() {
            //List<AllDefects> defects;
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < defects.size(); i++) {
                if (defects.get(i).getNum() > 0) {
                    stringBuilder.append(defects.get(i).getItemCode()).append("、").append(defects.get(i).getItemName()).append("*").append(defects.get(i).getNum()).append(";");
                }

            }
            if (StringUtils.isEmpty(stringBuilder.toString())) {
                return "";
            }
            return stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
            /*LogUtil.e("results = "+results);
            StringBuffer buffer=new StringBuffer();
            for (int i = 0; i < results.size(); i++) {
                if (results.get(i)!=0){
                    buffer.append(defects.get(i).getItemCode()+"、"+defects.get(i).getItemName()+"*"+results.get(i).toString()+";");
                }
            }
            if(StringUtils.isEmpty(buffer.toString())){
                return "";
            }
            return buffer.toString().substring(0,buffer.toString().length()-1);*/
        }

        public int getsum(){
            int sum=0;
            for (int i = 0; i < defects.size(); i++) {
                if (defects.get(i).getNum() > 0) {
                    sum = sum+defects.get(i).getNum();
                }

            }
            return sum;
        }

        public void setDefects(String str){
            LogUtil.e("str = "+str);
            String[] items=str.split(";");
            for (String item:items
                    ) {
                try{
                    String name=item.split("、|\\*")[0];
                    String num=item.split("、|\\*")[2];
                    for (AllDefects item2 :defects ) {
                        if (item2.getItemCode().equals(name)){
                            item2.setNum(Integer.parseInt(num));
                        }
                    }
                }catch (Exception e){

                }

            }
            notifyDataSetChanged();


        }

       /* public int getsum(){
            int sum=0;
            for (int i = 0; i < results.size(); i++) {
                sum+=results.get(i);
            }
            return sum;
        }


        public String getresult(){

            LogUtil.e("results = "+results);
            StringBuffer buffer=new StringBuffer();
            for (int i = 0; i < results.size(); i++) {
                if (results.get(i)!=0){
                    buffer.append(defects.get(i).getItemCode()+"、"+defects.get(i).getItemName()+"*"+results.get(i).toString()+";");
                }
            }
            if(StringUtils.isEmpty(buffer.toString())){
                return "";
            }
            return buffer.toString().substring(0,buffer.toString().length()-1);
        }*/

        /*public void setDefects(String str){
            String[] items=str.split(";");
            for (String item:items
                 ) {
                try{
                    String name=item.split("、|\\*")[0];
                    String num=item.split("、|\\*")[2];
                    for (AllDefects item2 :defects ) {
                        if (item2.getItemCode().equals(name)){
                            item2.setNum(Integer.parseInt(num));
                        }
                    }
                }catch (Exception e){

                }

            }
            notifyDataSetChanged();


        }*/
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void SDefectNo(Integer num) {
        sum = num.intValue();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void initDefectNo(String str) {
        initstr = str;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
